#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QDebug>
#include <QMessageBox>

ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);

    isStart = true;

    //设置初始进度条值
    ui->progressBar->setValue(0);

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
       QByteArray array = tcpSocket->readAll();

       if(true == isStart){ //代表发送过来的时文件信息
           isStart = false;

           //接收文件信息并拆包
           //hello##1024 拆包  section
           fileName = QString(array).section("##",0,0);
           fileSize = QString(array).section("##",1,1).toInt();

           recvSize = 0;

           file.setFileName(fileName);
           //创建文件设置为只写
           bool isOK = file.open(QIODevice::WriteOnly);
           if(false == isOK){
               qDebug() << "文件打开失败";

               tcpSocket->disconnectFromHost();
               tcpSocket->close();
           }

           //初始化进度条
           ui->progressBar->setMinimum(0);
           ui->progressBar->setMaximum(fileSize/1024);//qint64->int
           ui->progressBar->setValue(0);

       } else { //代表发送过来的时文件内容
            qint64 len = file.write(array);
            recvSize += len;

//            更新进度条
            ui->progressBar->setValue(recvSize/1024);
            if(recvSize == fileSize){//文件已全部接收
                QMessageBox::information(this,"完成","文件已全部接收");
                tcpSocket->write("file done");

                file.close();//关闭文件

                tcpSocket->disconnectFromHost();
                tcpSocket->close();
            }

       }

    });
}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_buttonConnect_clicked()
{
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toInt();

    tcpSocket->connectToHost(ip,port);
}
